package com.umeox.moto.watch.themes.app;

import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.umeox.moto.watch.themes.R;
import com.umeox.moto.watch.themes.skin.entity.DynamicAttr;
import com.umeox.moto.watch.themes.skin.listener.IDynamicNewView;
import com.umeox.moto.watch.themes.skin.listener.IResourceChangedListener;
import com.umeox.moto.watch.themes.skin.loader.ResourceManager;
import com.umeox.moto.watch.themes.skin.loader.SkinInflaterFactory;
import com.umeox.moto.watch.themes.util.SystemBarTintManager;
import com.umeox.watch.moto.dataservice.constants.Constants;

import java.lang.reflect.Field;
import java.util.List;

import uk.co.chrisjenx.calligraphy.CalligraphyContextWrapper;


public class ThemeAppCompatActivity extends AppCompatActivity implements ThemeManager.OnThemeChangedListener, IDynamicNewView, IResourceChangedListener {
    protected ThemeManager themeManager;
    protected Context mContext;
    private SkinInflaterFactory mSkinInflaterFactory;
    protected SystemBarTintManager mTintManager;

    private static final int THEME_DARK = 0;
    private static final int THEME_LIGHT = 1;
    public boolean isShowing = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        mContext = getApplicationContext();
        themeManager = ThemeManager.getInstance();
        if (!themeManager.isInitialized()) {
            Log.i("skin", "onCreate: initSkin" + this.getLocalClassName());
            themeManager.setup(this);
        }
        themeManager.registerOnThemeChangedListener(this);
        setTheme(themeManager.getCurrentStyle(this));
        setCustomTheme();
        try {
            Field field = LayoutInflater.class.getDeclaredField("mFactorySet");
            field.setAccessible(true);
            field.setBoolean(getLayoutInflater(), false);
            mSkinInflaterFactory = new SkinInflaterFactory();
            getLayoutInflater().setFactory(mSkinInflaterFactory);

        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onCreate(savedInstanceState);
        //setStatusBarMode();
        registerUnbindAndDisableReceiver(true);
    }

    /**
     * 注册\反注册解绑和上课禁用广播,退出当前界面返回时钟界面
     *
     * @param register
     */
    protected void registerUnbindAndDisableReceiver(boolean register) {
        if (register) {
            final IntentFilter intentFilter = new IntentFilter(Constants.ACTION_UNBIND);
            intentFilter.addAction(Constants.ACTION_ENABLE_FEATURES);
            registerReceiver(mUnbindAndDisableReceiver, intentFilter);
        } else {
            unregisterReceiver(mUnbindAndDisableReceiver);
        }

    }

    protected void setCustomTheme() {
        themeManager.initSkin();
    }

    private final BroadcastReceiver mUnbindAndDisableReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action == null) {
                return;
            }
            switch (action) {
                case Constants.ACTION_UNBIND:
                case Constants.ACTION_ENABLE_FEATURES:
                    finish();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        setTheme();
    }

    private void setTheme() {
        int styleResId = themeManager.getCurrentStyle(this);
        final int themeResId = getThemeResId(getTheme());
        if (themeResId != styleResId) {
            setTheme(styleResId);
        }
    }

    private int getThemeResId(Resources.Theme theme) {
        try {
            Field fThemeResId = theme.getClass().getDeclaredField("mThemeResId");
            if (!fThemeResId.isAccessible()) {
                fThemeResId.setAccessible(true);
            }
            return fThemeResId.getInt(theme);
        } catch (Exception e) {
            return -1;
        }
    }

    @Override
    public void onThemeChanged(@Nullable ThemeManager.OnThemeChangedEvent event) {
        setTheme();

    }

    @Override
    public void onResourceChanged() {
        Log.e("onResourceChanged", "onResourceChanged");
        mSkinInflaterFactory.applySkin();
        recreate();
    }

    @Override
    public void dynamicAddView(View view, List<DynamicAttr> pDAttrs) {
        mSkinInflaterFactory.dynamicAddSkinEnableView(this, view, pDAttrs);

    }

    @Override
    protected void onResume() {
        super.onResume();
        isShowing = true;
        ResourceManager.getInstance().attach(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        isShowing = false;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        isShowing = false;
        registerUnbindAndDisableReceiver(false);
        if (themeManager != null) {
            themeManager.unregisterOnThemeChangedListener(this);
        }
        ResourceManager.getInstance().detach(this);
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    public void makeStatusBarTransparent() {
        Window window = getWindow();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            int option = View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
            window.getDecorView().setSystemUiVisibility(option);
            window.setStatusBarColor(Color.TRANSPARENT);

        } else {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }


    private void setStatusBarMode() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            //6.0以上，调用系统方法
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            if (themeManager.getCurrentTheme() == THEME_LIGHT) {
                //设置状态栏文字颜色及图标为深色
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            } else {
                //设置状态栏文字颜色及图标为浅色
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            }
        }
    }

    /**
     * android 4.4 以上启用变色状态栏
     */
    @TargetApi(19)
    public void setStatusBarTintColor(int... color) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            mTintManager = new SystemBarTintManager(this);
            mTintManager.setStatusBarTintColor(color.length == 0 ? getResources().getColor(R.color.dark_colorAccent) : getResources().getColor(color[0]));
            mTintManager.setStatusBarTintEnabled(true);

            makeStatusBarTransparent();
        }
    }

}
